package com.csf.controller;

import com.csf.config.likeKeyConfig;
import com.csf.entity.Comment;
import com.csf.entity.DiscussPost;
import com.csf.entity.Event;
import com.csf.entity.SessionReplace;
import com.csf.event.EventProducer;
import com.csf.service.CommentService;
import com.csf.service.DiscussPostService;
import com.csf.util.CommunityActivation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.xml.ws.Action;
import java.util.Date;

@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityActivation {

    @Autowired
    private SessionReplace sessionReplace;

    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/insertComment/{discussPostId}",method = RequestMethod.POST)
    public String insertComment(@PathVariable("discussPostId") int discussPostId, Comment comment){
        comment.setCreateTime(new Date());
        comment.setStatus(0);
        //当前能够评论的人是登录人员
        comment.setUserId(sessionReplace.getUser().getId());
        commentService.insertComment(comment);

        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setUserId(comment.getUserId())
                .setData("postId",discussPostId);

//        判断当前到底是评论帖子还是回复评论
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            DiscussPost discussPost = discussPostService.selectDisById(comment.getEntityId());
            event.setEntityUserId(discussPost.getUserId());
        }else if (comment.getEntityType() == ENTITY_TYPE_COMMENT){
            Comment target = commentService.selectCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);
//       当帖子被评论时，帖子可能会改变，所以需要再次在es中改变一次(如果与帖子相关的评论就直接进行操作)
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            event = new Event()
                    .setTopic(TOPIC_DISES)
                    .setEntityId(comment.getEntityId())
                    .setEntityType(ENTITY_TYPE_POST)
                    .setUserId(comment.getUserId());
            eventProducer.fireEvent(event);
//            当帖子被评论时，会对帖子的热度有影响
            String postKey = likeKeyConfig.getPostKey();
            redisTemplate.opsForSet().add(postKey,discussPostId);
        }
        return "redirect:/discuss/detail/"+discussPostId;
    }
}
